package com.qf.mybatis01;

import com.qf.mybatis01.entity.User;
import org.junit.Test;

import java.sql.*;

public class JdbcTest1 {

    @Test
    public void testJdbc() throws ClassNotFoundException, SQLException {

        //1. 加载数据库驱动程序
        Class.forName("com.mysql.jdbc.Driver");

        //2. 创建数据库连接对象
        final Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false", "root", "root");

        //3. 创建 statement对象
        String sql = "select * from t_users where id=?";
        final PreparedStatement statement = connection.prepareStatement(sql);

        statement.setInt(1,2);  // 为sql中的问号赋值

        //4. 执行sql,获得结果集对象
        final ResultSet resultSet = statement.executeQuery();

        while (resultSet.next()) {

            // 获取 结果集中的数据
            final int id = resultSet.getInt("id");
            final String name = resultSet.getString("name");
            final String password = resultSet.getString("password");
            final String sex = resultSet.getString("sex");

            // 手动映射成 java对象
            final User user = new User();
            user.setId(id);
            user.setName(name);
            user.setPassword(password);
            user.setSex(sex);

            System.out.println(user);

        }

        // 关闭资源
        resultSet.close();
        statement.close();
        connection.close();

    }
}
